package com.cc.tojsonscheam.ds;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.cc.tojsonscheam.victools.TestEntity;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 根据数据库生成Json-Schema
 * @author cc
 * @date 2022/8/30
 **/
public class GeneratorTest {
    @Autowired
    GeneratorJsonMapper generatorJsonMapper;


    /**
     * 生成yapi JSON Schema
     * 不适合级联=自己改造
     * <p>
     * {
     * "type": "object",
     * "properties": {
     * "id": {
     * "description": "售后单数据id",
     * "type": "integer"
     * }
     * }
     * }
     */
    public void generatorJson() {
        Map<String, Object> root = new HashMap<>();
        Map<String, Object> child = new HashMap<>();
        Map<String, Object> comment = new HashMap<>();
        //修改这个 就可以了

        Class<TestEntity> clazz = TestEntity.class;
        String value = clazz.getAnnotation(TableName.class).value();
        String dsName="test";
        List<Map<String, Object>> mapList = generatorJsonMapper.selectTableInfo(dsName,value);
        for (Map<String, Object> map : mapList) {
            comment.put(map.get("name").toString(), map.get("comment"));
        }

        TableInfo tableInfo = TableInfoHelper.getTableInfo(clazz);
        List<TableFieldInfo> fieldList = tableInfo.getFieldList();
        for (TableFieldInfo fieldInfo : fieldList) {
            Map<String, Object> child1 = new HashMap<>();
            child1.put("description", comment.get(fieldInfo.getColumn()));
            Class<?> propertyType = fieldInfo.getPropertyType();
            String type = propertyType.getSimpleName().toLowerCase();
            if (propertyType == LocalDateTime.class) {
                type = "string";
            } else if (propertyType == Long.class) {
                type = "number";
            }
            child1.put("type", type);
            child.put(fieldInfo.getProperty(), child1);
        }
        root.put("type", "object");
        root.put("properties", child);
        System.out.println(JSON.toJSONString(root));
    }

}